package com.guardian.communication.nettry.handler;

import com.guardian.command.CommandManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.util.Arrays;

/**
 * 消息处理
 * @author: huwei
 * @date: 2019/10/10 16:59
 * @version: 1.0.0
 */
@ChannelHandler.Sharable
public class MessageServerHandler extends ChannelInboundHandlerAdapter {

    private static final String MESSAGE_SPLIT_SYMBOL = "\t";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String message = (String) msg;
            String[] ins = message.split(MESSAGE_SPLIT_SYMBOL);
            String command = null;
            String[] args = ins;

            if (ins.length != 0) {
                command = ins[0];
                args = new String[ins.length - 1];
                System.arraycopy(ins, 1, args, 0, args.length);
            }
            String resMsg = CommandManager.executorCommand(command, args);
            ctx.writeAndFlush(resMsg == null ? "" : resMsg);
        }finally {
            ReferenceCountUtil.release(msg);
        }
    }

}